package com.qqtech.qquan.mall.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.util.PinyingUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.mall.enums.MallProductStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallSupplierStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallSupplierTypeDictEnum;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallProductQuery;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.model.MallSupplierQuery;
import com.qqtech.qquan.mall.model.MallSupplierUser;
import com.qqtech.qquan.mall.model.MallSupplierUserVo;
import com.qqtech.qquan.mall.model.MallSupplierVo;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.mall.service.MallSupplierUserService;
import com.qqtech.qquan.sys.controller.BaseAdminController;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.service.UserBaseService;

@Controller
@RequestMapping(value = "/mall/supplier")
public class MallSupplierController extends BaseAdminController {
	@Resource
	private MallSupplierService mallSupplierService;
	@Resource
	private CommunityBaseService communityBaseService;
	@Resource 
	private MallSupplierUserService mallSupplierUserService;
	@Resource 
	private UserBaseService userBaseService;
	@Resource
	private MallProductService mallProductService;
    
	@Override
	protected BaseService<MallSupplier> getBaseService() {
		return mallSupplierService;
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		return "/mall/supplier-list";
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(MallSupplierQuery query, HttpServletRequest request,
			HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(),
				new PageOrder(Direction.ASC, "oidx"));
		Page<MallSupplierVo> page = mallSupplierService.queryPageList(query,
				pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		return "/mall/supplier-update";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(MallSupplierVo mallSupplierVo, HttpServletRequest request,
			HttpServletResponse response) {
		Result ret = new Result();
		if (mallSupplierVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(mallSupplierVo.getName())) {
				ret.addErr("请输入供应商名称");
			}
			if (mallSupplierVo.getStatus() == null) {
				ret.addErr("状态不能为空");
			}
			if (mallSupplierVo.getIsShow() == null) {
				ret.addErr("请选择是否首页展示");
			}
			if (mallSupplierVo.getType() == null) {
				ret.addErr("请选择供应商类型");
			} else {
				if (mallSupplierVo.getType().intValue() == MallSupplierTypeDictEnum.LOCAL.getCode()) {//本地商家
					if (mallSupplierVo.getCommunityId() == null) {
						ret.addErr("本地商家的供应商要选择所在社区");
					}
					if (mallSupplierVo.getUserId() == null) {
						ret.addErr("本地商家的供应商要选择关联用户");
					}
					if (StringUtil.isBlank(mallSupplierVo.getAddress())) {
						ret.addErr("请填写地址");
					}
					if (StringUtil.isBlank(mallSupplierVo.getPhone())) {
						ret.addErr("请填写电话");
					}
					if (mallSupplierVo.getRate().compareTo(new BigDecimal("1.50")) == 1) {
						ret.addErr("分账比例不能大于1.5");
					}
					if (mallSupplierVo.getRate().compareTo(BigDecimal.ZERO) == -1) {
						ret.addErr("分账比例不能小于0");
					}
				}
			}
			
		}
		if (ret.checkForm()) {
			//获取用户对应的供应商
			if (mallSupplierVo.getUserId() != null
					&& mallSupplierVo.getType() != null
					&& mallSupplierVo.getType().intValue() == 2) {
				MallSupplierUser query = new MallSupplierUser();
				query.setUserId(mallSupplierVo.getUserId());
				List<MallSupplierUser> tempList = mallSupplierUserService.queryList(query);
				if(tempList != null && tempList.size() > 0){
					ret.addErr("用户已关联其他供应商");
					return ret;
				}
			}
			
			MallSupplier mallSupplier = new MallSupplier();
			mallSupplier.setName(mallSupplierVo.getName().trim());
			MallSupplierVo ms = mallSupplierService.getByName(mallSupplierVo.getName().trim());
			if(ms != null){
				ret.addErr("供应商名称不能重复");
				return ret;
			}
			Timestamp now = TimeUtil.now();
			mallSupplier.setType(mallSupplierVo.getType());
			mallSupplier.setShortName(mallSupplierVo.getShortName());
			mallSupplier.setStatus(mallSupplierVo.getStatus());
			if (mallSupplierVo.getLogo() == null) {
				mallSupplier.setLogo("");
			} else {
				mallSupplier.setLogo(mallSupplierVo.getLogo());
			}
			mallSupplier.setNewAt(now);
			mallSupplier.setUpdAt(now);
			mallSupplier.setFirstLetter(PinyingUtil.getPinYin(mallSupplier.getName().substring(0,1),true));
			if (mallSupplierVo.getResume() == null) {
				mallSupplier.setResume("");
			} else {
				mallSupplier.setResume(mallSupplierVo.getResume().trim());
			}
			mallSupplier.setUrl(mallSupplierVo.getUrl());
			mallSupplier.setResumeImg(mallSupplierVo.getResumeImg());
			mallSupplier.setIsShow(mallSupplierVo.getIsShow());
			mallSupplier.setBanner(mallSupplierVo.getBanner());
			mallSupplier.setBgImg(mallSupplierVo.getBgImg());
			mallSupplier.setDescription(mallSupplierVo.getDescription());
			mallSupplier.setOidx(0);
			if(mallSupplierVo.getOidx() != null){
				mallSupplier.setOidx(mallSupplierVo.getOidx());
			}
			mallSupplier.setSubtitle(mallSupplierVo.getSubtitle());
			mallSupplier.setSubjectImg(mallSupplierVo.getSubjectImg());
			mallSupplier.setFirstImg(mallSupplierVo.getFirstImg());
			if (mallSupplierVo.getType().intValue() == MallSupplierTypeDictEnum.EXTERNAL.getCode()) {
				mallSupplier.setCommunityId(0);
			} else {
				mallSupplier.setCommunityId(mallSupplierVo.getCommunityId());
			}
			mallSupplier.setAddress(mallSupplierVo.getAddress()==null?"":mallSupplierVo.getAddress().trim());
			mallSupplier.setPhone(mallSupplierVo.getPhone()==null?"":mallSupplierVo.getPhone().trim());
			mallSupplier.setRate(mallSupplierVo.getRate());
			
			Integer supplierId = mallSupplierService.insert(mallSupplier);
			
			//本地供应商关联前台用户
			if (supplierId != null
					&& mallSupplierVo.getType().intValue() == MallSupplierTypeDictEnum.LOCAL.getCode() 
						&& mallSupplierVo.getUserId() != null) {
				MallSupplierUser msu = new MallSupplierUser();
				msu.setSupplierId(supplierId);
				msu.setUserId(mallSupplierVo.getUserId());
				msu.setNewAt(TimeUtil.now());
				mallSupplierUserService.insert(msu);
			}
		}
		return ret;
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) {
		MallSupplierVo mallSupplierVo = mallSupplierService.getById(id);
		if(mallSupplierVo != null){
			if (mallSupplierVo.getCommunityId() != null && mallSupplierVo.getCommunityId().intValue() != 0) {
				CommunityBaseVo community = communityBaseService.getById(mallSupplierVo.getCommunityId());
				if (community != null) {
					mallSupplierVo.setCommunityName(community.getName());
				}
			}
			MallSupplierUserVo temp = new MallSupplierUserVo();
			temp.setSupplierId(mallSupplierVo.getId());
			List<MallSupplierUserVo> msuList = mallSupplierUserService.queryList(temp);
			if(msuList != null && msuList.size() > 0){
				MallSupplierUserVo msu = msuList.get(0);
				UserBase user = userBaseService.getById(msu.getUserId());
				if(user != null){
					mallSupplierVo.setUserId(user.getId());
					mallSupplierVo.setUserInfo(user.getNick());
				}
			}
			
		}
		
		request.setAttribute("mallSupplierVo", mallSupplierVo);
		return "/mall/supplier-update";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(MallSupplierVo mallSupplierVo) {
		Result ret = new Result();
		if (mallSupplierVo == null || mallSupplierVo.getId() == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(mallSupplierVo.getName())) {
				ret.addErr("请输入供应商名称");
			}
			if (mallSupplierVo.getStatus() == null) {
				ret.addErr("状态不能为空");
			}
			if (mallSupplierVo.getIsShow() == null) {
				ret.addErr("请选择是否首页展示");
			}
			if (mallSupplierVo.getType() == null) {
				ret.addErr("请选择供应商类型");
			} else {
				if (mallSupplierVo.getType().intValue() == MallSupplierTypeDictEnum.LOCAL.getCode()) {//本地商家
					if (mallSupplierVo.getCommunityId() == null) {
						ret.addErr("本地商家的供应商要选择所在社区");
					}
					if (StringUtil.isBlank(mallSupplierVo.getAddress())) {
						ret.addErr("请填写地址");
					}
					if (StringUtil.isBlank(mallSupplierVo.getPhone())) {
						ret.addErr("请填写电话");
					}
					if (mallSupplierVo.getRate().compareTo(new BigDecimal("1.50")) == 1) {
						ret.addErr("分账比例不能大于1.5");
					}
					if (mallSupplierVo.getRate().compareTo(BigDecimal.ZERO) == -1) {
						ret.addErr("分账比例不能小于0");
					}
				}
			}
		}
		if (ret.checkForm()) {
			//获取用户对应的供应商
			if(mallSupplierVo.getUserId() != null){
				MallSupplierUser query = new MallSupplierUser();
				query.setUserId(mallSupplierVo.getUserId());
				List<MallSupplierUser> msuList = mallSupplierUserService.queryList(query);
				if(msuList != null && msuList.size() > 0){
					MallSupplierUser tempUser = msuList.get(0);
					if(mallSupplierVo.getId() != tempUser.getSupplierId()){
						ret.addErr("用户已关联其他供应商");
						return ret;
					}
				}
			}
			
			MallSupplier update = new MallSupplier();
			update.setName(mallSupplierVo.getName().trim());
			MallSupplierVo ms = mallSupplierService.getByName(mallSupplierVo.getName().trim());
			if(ms != null && ms.getId().intValue() != mallSupplierVo.getId().intValue()){
				ret.addErr("供应商名称不能重复");
				return ret;
			}
			update.setId(mallSupplierVo.getId());
			update.setType(mallSupplierVo.getType());
			update.setShortName(mallSupplierVo.getShortName());
			if (mallSupplierVo.getResume() == null) {
				update.setResume("");
			} else {
				update.setResume(mallSupplierVo.getResume().trim());
			}
			update.setLogo(mallSupplierVo.getLogo());
			update.setStatus(mallSupplierVo.getStatus());
			update.setUpdAt(TimeUtil.now());
			update.setIsShow(mallSupplierVo.getIsShow());
			update.setUrl(mallSupplierVo.getUrl());
			update.setFirstLetter(PinyingUtil.getPinYin(update.getName().substring(0,1),true));
			if(StringUtil.isNotBlank(mallSupplierVo.getResumeImg())){
				update.setResumeImg(mallSupplierVo.getResumeImg());
			}
			if(StringUtil.isNotBlank(mallSupplierVo.getBanner())){
				update.setBanner(mallSupplierVo.getBanner());
			}
			if(StringUtil.isNotBlank(mallSupplierVo.getBgImg())){
				update.setBgImg(mallSupplierVo.getBgImg());
			}
			update.setDescription(mallSupplierVo.getDescription());
			update.setOidx(mallSupplierVo.getOidx());
			update.setSubtitle(mallSupplierVo.getSubtitle());
			update.setSubjectImg(mallSupplierVo.getSubjectImg());
			update.setFirstImg(mallSupplierVo.getFirstImg());
			if (mallSupplierVo.getType().intValue() == MallSupplierTypeDictEnum.EXTERNAL.getCode()) {
				update.setCommunityId(0);
			} else {
				update.setCommunityId(mallSupplierVo.getCommunityId());
			}
			update.setAddress(mallSupplierVo.getAddress());
			update.setPhone(mallSupplierVo.getPhone());
			update.setRate(mallSupplierVo.getRate());
			mallSupplierService.updateById(update);
			
			//本地供应商关联用户
			if (mallSupplierVo.getId() != null
					&& mallSupplierVo.getType().intValue() == MallSupplierTypeDictEnum.LOCAL.getCode() 
						&& mallSupplierVo.getUserId() != null) {
				MallSupplierUser msu = new MallSupplierUser();
				msu.setSupplierId(mallSupplierVo.getId());
			    List<MallSupplierUser> tempList = mallSupplierUserService.queryList(msu);
			    if(tempList != null && tempList.size() > 0){
			    	 MallSupplierUser temp = tempList.get(0);
			    	 if(!temp.getUserId().equals(mallSupplierVo.getUserId())){
						mallSupplierUserService.delete(msu);
						msu.setUserId(mallSupplierVo.getUserId());
						msu.setNewAt(TimeUtil.now());
						mallSupplierUserService.insert(msu);
					}
			    }else{
					msu.setUserId(mallSupplierVo.getUserId());
					msu.setNewAt(TimeUtil.now());
					mallSupplierUserService.insert(msu);
				}		 	
			}
			//供应商失效，所有关联商品下架
			if(mallSupplierVo.getStatus().intValue() == MallSupplierStatusDictEnum.DELETE.getCode()
					&& mallSupplierVo.getStatus().intValue() != ms.getStatus().intValue()){
				MallProductQuery mallProductQuery = new MallProductQuery();
				mallProductQuery.setSupplierId(ms.getId());
				mallProductQuery.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
				List<MallProduct> productList = mallProductService.queryList(mallProductQuery);
				if(productList != null && productList.size() > 0){
					for(MallProduct mp : productList){
						mp.setStatus(MallProductStatusDictEnum.OFFSHELF.getCode());
					}
					mallProductService.updateInBatch(productList);
				}
			}
		}
		return ret;
	}
	
	@RequestMapping(value = "/imgUpload", method = RequestMethod.GET)
	public String imgUpload(Model model) {
		return "/mall/supplier-imgUpload";
	}
}
